package com.yimu.lib.http;



import com.yimu.lib.http.net.DefaultThreadFactory;
import com.yimu.lib.http.net.HttpAsyncTask;
import com.yimu.lib.http.net.HttpCallback;
import com.yimu.lib.http.net.HttpRequest;
import com.yimu.lib.http.net.NetFuntion;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述：网络请求工具类
 * 创建者：  Churck
 * 创建时间：16/6/10 12:17
 * 修改者： Churck
 * 修改时间：16/6/10 12:17
 * 版 本：v1.0
 */
public class HttpUtils {
    private volatile static HttpUtils singleton;
    private Executor executor;
    private  HttpAsyncTask<NetFuntion> httpAsyncTask;
    private HttpUtils (){}
    public static HttpUtils getInstance() {
        if (singleton == null) {
            synchronized (HttpUtils.class) {
                if (singleton == null) {
                    singleton = new HttpUtils();
                }
            }
        }
        return singleton;
    }

    /**
     * 网络初始化
     */
    public void init(){
        BlockingQueue<Runnable> sPoolWorkQueue =new LinkedBlockingQueue<>(3);
        executor = new ThreadPoolExecutor(  3 , 8 , 1 , TimeUnit.SECONDS,sPoolWorkQueue, new DefaultThreadFactory() );
    }

    /**
     * 网络初始化
     * @param capacity
     * @param corePoolSize
     * @param maximumPoolSize
     * @param keepAliveTime
     */
    public void init(int capacity,int corePoolSize,
                     int maximumPoolSize,
                     long keepAliveTime){
        BlockingQueue<Runnable> sPoolWorkQueue =new LinkedBlockingQueue<>(capacity);
        executor = new ThreadPoolExecutor(  corePoolSize , maximumPoolSize , keepAliveTime , TimeUnit.SECONDS,sPoolWorkQueue, new DefaultThreadFactory() );
    }

    /**
     * 网络请求
     * @param url
     * @param data
     * @param method
     * @param callback
     */
    public  void requestStringhttp(String url, Map<String, String> data, String method,HttpCallback callback) {
        NetFuntion netFuntion=new NetFuntion();
        netFuntion.setUrl(url);
        netFuntion.setData(data);
        netFuntion.setMethod(method);
        requestString(netFuntion, callback);
    }
    public void canleClose(){
        if (null!=httpAsyncTask){
            httpAsyncTask.cancle();
            httpAsyncTask=null;
        }
    }
    private  void requestString(NetFuntion funtion,HttpCallback callback) {
        httpAsyncTask = new HttpAsyncTask<>();
        httpAsyncTask .setCallback(new HttpRequest(callback));
        httpAsyncTask.executeOnExecutor(executor,funtion);
    }
}
